package com.jacky.ws.config;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.jacky.ws.handler.SocketEventHandler;
import com.jacky.ws.properties.SocketIOProperties;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Optional;

@Configuration
public class SocketIOConfig {

    private final Logger LOG = LoggerFactory.getLogger(SocketIOConfig.class);

    private final SocketIOProperties properties;

    public SocketIOConfig(SocketIOProperties properties) {
        this.properties = properties;
    }

    @Resource
    SocketEventHandler eventHandler;

    @Bean(name = "socketServer")
    public SocketIOServer createSocketIOServer() {
        LOG.info("创建 SocketIOServer 开始");
        SocketConfig sConfig = new SocketConfig();
        sConfig.setTcpNoDelay(true);
        sConfig.setTcpKeepAlive(true);

        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(sConfig);
        config.setHostname(properties.getHostname());
        config.setPort(properties.getPort());
        config.setBossThreads(properties.getBossThreads());
        config.setWorkerThreads(properties.getWorkerThreads());
        config.setAllowCustomRequests(properties.getAllowCustomRequests());
        config.setUpgradeTimeout(properties.getUpgradeTimeout());
        config.setPingTimeout(properties.getPingTimeout());
        config.setPingInterval(properties.getPingInterval());
        SocketIOServer server = new SocketIOServer(config);
        Optional.ofNullable(properties.getNamespaces())
                .ifPresent(nss -> Arrays.stream(nss).forEach(
                        ns ->{
                            SocketIONamespace namespace = server.addNamespace(ns);
                            namespace.addListeners(eventHandler);
                        }));

        return server;
    }

    // 这个bean是用来扫描socketIo的注解,比如 @OnConnect/@OnEvent
    @Bean
    public SpringAnnotationScanner annotationScanner() {
        return new SpringAnnotationScanner(createSocketIOServer());
    }

}
